package com.fzkj.bio.part3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 实现服务端可以接收多个客户端的连接请求
 * 思路：
 *  1、应该一直调用accept方法监听
 *  2、当有连接请求就新开一个线程去处理
 */
public class Server {

    public static void main(String[] args) {
        startServer();
    }

    public static void startServer() {
        Socket socket = null;
        try {
            // 1、监听端口
            ServerSocket ss = new ServerSocket(2323);
            System.out.println("==== 服务端启动成功 ====");
            while(true) {
                // 等待客户端连接
                socket = ss.accept();
                // 交由一个新的线程去处理
                new Thread(new ServerReaderThread(socket)).start();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

/**
 * 处理客户端请求
 */
class ServerReaderThread implements Runnable {

    private Socket socket;

    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 获取输入流
            InputStream is = socket.getInputStream();
            // 包装成缓冲字符输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String msg;
            // 接收消息
            while((msg = br.readLine()) != null) {
                System.out.println("接收到客户端 " + socket.getLocalPort() + " 的消息：" + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
